#include "QTrssViewMdTitle.h"
#include "ui_QTrssViewMdTitle.h"

#include <QRegularExpression>

QTrssViewMdTitle::QTrssViewMdTitle(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::QTrssViewMdTitle)
{
    ui->setupUi(this);

}

QTrssViewMdTitle::~QTrssViewMdTitle()
{
    delete ui;
}


void QTrssViewMdTitle::get_markdown_title_tree(QStandardItemModel * tocModel,QString markdownText)
{

    QRegularExpression headingRegex("^(#{1,6})\\s+(.*)$", QRegularExpression::MultilineOption);
    QRegularExpressionMatchIterator matchIterator = headingRegex.globalMatch(markdownText);

    QList<QStandardItem*> parentItems;
    parentItems.append(nullptr);
    int title_cnt = 0;
    while (matchIterator.hasNext())
    {
        QRegularExpressionMatch match = matchIterator.next();
        QString title = match.captured(2);
        int level = match.captured(1).length();

        // get parrent items
        while (parentItems.size() > level) {
            parentItems.removeLast();
        }
        while (parentItems.size() < level) {
            parentItems.append(nullptr);
        }

        QStandardItem *parent = parentItems[level - 1];
        QString itemText = title; //获取目录地标题
        QStandardItem *item = new QStandardItem(itemText);

        if (parent) {
            parent->appendRow(item);
        } else {
            tocModel->appendRow(item);
        }

        // update parrent items
        if (parentItems.size() == level) {
            parentItems.append(item);
        } else {
            parentItems[level] = item;
        }
        title_cnt ++;
    }
}
